<template>
  <!-- 规格弹窗 -->
  <su-popup :show="authType !== ''" round="10" :showClose="true" @close="closeAuthModal">
    <view class="login-wrap">
      <!-- 1. 账号密码登录 accountLogin -->
      <account-login
        v-if="authType === 'accountLogin'"
        :agreeStatus="state.protocol"
        @onConfirm="onConfirm"
      />

      <!-- 2.短信登录  smsLogin -->
      <sms-login v-if="authType === 'smsLogin'" :agreeStatus="state.protocol" @onConfirm="onConfirm" />

      <!-- 3.短信注册 smsRegister-->
      <sms-register
        v-if="authType === 'smsRegister'"
        :agreeStatus="state.protocol"
        @onConfirm="onConfirm"
      />

      <!-- 4.忘记密码 resetPassword-->
      <reset-password v-if="authType === 'resetPassword'" />

      <!-- 5.绑定手机号 changeMobile -->
      <change-mobile v-if="authType === 'changeMobile'" />

      <!-- 6.修改密码 changePassword-->
      <change-passwrod v-if="authType === 'changePassword'" />

      <!-- 7.修改用户名 changeUsername-->
      <change-username v-if="authType === 'changeUsername'" />

      <!-- 8.微信小程序授权 changeUsername-->
      <mp-authorization v-if="authType === 'mpAuthorization'" />

      <!-- 第三方登录+注册 -->
      <view
        v-if="['accountLogin', 'smsLogin'].includes(authType)"
        class="auto-login-box ss-flex ss-flex-col ss-row-center ss-col-center"
      >
        <!-- 立即注册&快捷登录 TextButton -->
        <view v-if="sheep.$platform.name === 'WechatMiniProgram'" class="ss-flex register-box" style="width: 100%;">
         <!-- <view class="register-title">还没有账号?</view> -->
          <!-- <button class="ss-reset-button register-btn" @tap="showAuthModal('smsRegister')"
            >立即注册</button
          >
          <view class="or-title">或</view> -->
		
          <!-- <button class="ss-reset-button login-btn" @tap="thirdLogin('wechat')">
			  <image
			    style='width:50px;height:50px'
			    :src="
			      sheep.$url.static('/assets/addons/shopro/uniapp/platform/WechatMiniProgram.png')
			    "
			  />
			  微信一键登录
			  </button>  -->
        <button v-if="state.protocol" type="default" class="loginTv1" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">手机号快捷登录</button>
        <button v-if="!state.protocol" type="default" class="loginTv1" @click="gethuoqu">手机号快捷登录</button>
          <!-- <view class="circle"></view> -->
        
        </view>

        <button
          v-if="sheep.$platform.name !== 'WechatMiniProgram'"
          class="ss-reset-button type-btn"
          @tap="showAuthModal('smsRegister')"
        >
          立即注册
        </button>

        <!-- 公众号|App微信登录 -->
        <button
          v-if="
            ['WechatOfficialAccount', 'App'].includes(sheep.$platform.name) &&
            sheep.$platform.isWechatInstalled
          "
          @tap="thirdLogin('wechat')"
          class="ss-reset-button auto-login-btn"
        >
          <image
            class="auto-login-img"
            :src="sheep.$url.static('/assets/addons/shopro/uniapp/platform/wechat.png')"
          ></image>
        </button>

        <!-- iOS登录 -->
        <button
          v-if="sheep.$platform.os === 'ios' && sheep.$platform.name === 'App'"
          @tap="thirdLogin('apple')"
          class="ss-reset-button auto-login-btn"
        >
          <image
            class="auto-login-img"
            :src="sheep.$url.static('/assets/addons/shopro/uniapp/platform/apple.png')"
          ></image>
        </button>
      </view>

      <view class="nologin" @click="closeAuthModal">暂不登录</view>
      <view
        v-if="['accountLogin', 'smsLogin', 'smsRegister'].includes(authType)"
        class="agreement-box ss-flex ss-row-center"
        :class="{ shake: currentProtocol }"
      >
        <label class="radio ss-flex ss-col-center" @tap="onChange">
          <radio
            :checked="state.protocol"
            color="var(--ui-BG-Main)"
            style="transform: scale(0.8)"
            @tap.stop="onChange"
          />
          <view class="agreement-text ss-flex ss-col-center ss-m-l-8">
            我已阅读并遵守
            <view
              class="tcp-text"
              @tap.stop="onProtocol(appInfo.user_protocol.id, appInfo.user_protocol.title)"
            >
              《{{ appInfo.user_protocol.title }}》
            </view>
            <view class="agreement-text">与</view>
            <view
              class="tcp-text"
              @tap.stop="onProtocol(appInfo.privacy_protocol.id, appInfo.privacy_protocol.title)"
            >
              《{{ appInfo.privacy_protocol.title }}》
            </view>
          </view>
        </label>
      </view>
      <view class="safe-box"></view>
    </view>
  </su-popup>
</template>

<script setup>
  import { computed, reactive, ref,watch } from 'vue';
  import sheep from '@/sheep';
  import accountLogin from './components/account-login.vue';
  import smsLogin from './components/sms-login.vue';
  import smsRegister from './components/sms-register.vue';
  import resetPassword from './components/reset-password.vue';
  import changeMobile from './components/change-mobile.vue';
  import changePasswrod from './components/change-password.vue';
  import changeUsername from './components/change-username.vue';
  import mpAuthorization from './components/mp-authorization.vue';
  import { closeAuthModal, showAuthModal } from '@/sheep/hooks/useModal';

  const appInfo = computed(() => sheep.$store('app').info);

  const modalStore = sheep.$store('modal');
  // 授权弹窗类型
  // console.log(modalStore.auth)
  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
console.log(curRoute) 
let authType = computed(() => curRoute == 'pages/index/index'?'':modalStore.auth); 
// if(curRoute == 'pages/index/index'){
//   console.log("不显示登录弹窗")
//   authType = ''
// }
  const props = defineProps({
    tabbar: {
      type: [String, Boolean],
      default: '',
    },
  })
  watch(
    () => props.tabbar,
    (newValue, oldValue) => {
      console.log("++++底部路由")
      console.log(newValue)
    },
  );
  const state = reactive({
    protocol: false,
    detail:{}
  });

  const currentProtocol = ref(false);

  //勾选协议
  function onChange() {
    state.protocol = !state.protocol;
  }

  // 查看协议
  function onProtocol(id, title) {
    closeAuthModal();
    sheep.$router.go('/pages/public/richtext', {
      id,
      title,
    });
  }

  // 点击登录/注册事件
  function onConfirm(e) {
    currentProtocol.value = e;
    setTimeout(() => {
      currentProtocol.value = false;
    }, 1000);
  }
  function gethuoqu(){
    if(!state.protocol){
      sheep.$helper.toast('请勾选同意协议');
      return;
    }
    
  }
  async function decryptPhoneNumber(e){ 
      // console.log(e);
      // console.log("++++")
      // console.log(uni.getStorageSync('socketSessionId'))
      if (!state.protocol) {
        sheep.$helper.toast('请勾选同意协议');
        return
      }
      if(e.detail.errMsg == 'getPhoneNumber:ok'){
        // this.shuchu = JSON.stringify(e)
        // state.detail = e.detail
        // const res = await sheep.$api.goods.mobileRegister(e.detail);
        // console.log(res)
        // console.log("202行")
        // console.log(e.detail)
        let result = await sheep.$platform.useProvider().bindUserPhoneNumber(e.detail);
        if (result) {
          sheep.$store('user').getInfo();
          closeAuthModal();
        }
        
        // const userInfo = await sheep.$store('user').setToken(res.data.token);
        // const userInfo = await sheep.$store('user').getInfo();
      }else{
        sheep.$helper.toast('请先授权获取手机号');
        return
      }
      
    }

  // 第三方授权登陆
  const thirdLogin = async (provider) => {
    if (!state.protocol) {
      // TODO：协议div晃动效果
      currentProtocol.value = true;
      setTimeout(() => {
        currentProtocol.value = false;
      }, 1000);
      sheep.$helper.toast('请勾选同意');
      return;
    }
    // console.log(provider)
    const loginRes = await sheep.$platform.useProvider(provider).login();
    // console.log(loginRes)
    if (loginRes) {
      closeAuthModal();
      const userInfo = await sheep.$store('user').getInfo();
      // 触发小程序授权信息弹框
      // #ifdef MP-WEIXIN
      if (userInfo.third_oauth.length > 0) {
        const mpThirdOauthInfo = userInfo.third_oauth.find(
          (item) => item.platform === 'miniProgram',
        );
        if (mpThirdOauthInfo && !mpThirdOauthInfo.nickname) {
          showAuthModal('mpAuthorization');
        }
      }
      // #endif
    }
  };
</script>

<style lang="scss" scoped>
  @import './index.scss';

  .shake {
    animation: shake 0.05s linear 4 alternate;
  }

  @keyframes shake {
    from {
      transform: translateX(-10rpx);
    }
    to {
      transform: translateX(10rpx);
    }
  }

  .register-box {
    position: relative;
    justify-content: center;
    .register-btn {
      color: #999999;
      font-size: 30rpx;
      font-weight: 500;
    }
    .register-title {
      color: #999999;
      font-size: 30rpx;
      font-weight: 400;
      margin-right: 24rpx;
    }
    .or-title {
      margin: 0 16rpx;
      color: #999999;
      font-size: 30rpx;
      font-weight: 400;
    }
    .login-btn {
      color: var(--ui-BG-Main);
      font-size: 30rpx;
      font-weight: 500;
    }
    .circle {
      position: absolute;
      right: 0rpx;
      top: 18rpx;
      width: 8rpx;
      height: 8rpx;
      border-radius: 8rpx;
      background: var(--ui-BG-Main);
    }
  }
  .safe-box {
    height: calc(constant(safe-area-inset-bottom) / 5 * 3);
    height: calc(env(safe-area-inset-bottom) / 5 * 3);
  }

  .tcp-text {
    color: var(--ui-BG-Main);
  }

  .agreement-text {
    color: $dark-9;
  }
  .loginTv1 {
		width: 80%;
		margin-top: 70rpx;
		height: 88rpx;
		border-radius: 50rpx;
		// background-color: #D4FF45;
		background: #ff6d00 !important;
		// background: linear-gradient(0deg, rgb(252, 141, 0), rgb(254, 83, 1));
		color: #fff !important;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
  .nologin{
    color: #ff6d00;
    display: block;
    text-align: center;
    margin-top: 20rpx;
    font-size: 28rpx;
  }
</style>
